package server.demo.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import server.demo.entity.Order;
import server.demo.entity.Payment;
import server.demo.repository.OrderRepository;
import server.demo.repository.PaymentRepository;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Service
@Transactional
public class PaymentService {
    
    @Autowired
    private PaymentRepository paymentRepository;
    
    @Autowired
    private OrderRepository orderRepository;
    
    /**
     * 处理订单付款
     */
    public Payment processPayment(Long orderId, String paymentMethod) {
        Optional<Order> orderOpt = orderRepository.findById(orderId);
        if (orderOpt.isEmpty()) {
            throw new RuntimeException("订单不存在");
        }
        
        Order order = orderOpt.get();
        if (order.getOrderStatus() != Order.OrderStatus.PENDING) {
            throw new RuntimeException("订单状态不允许付款");
        }
        
        // 检查是否已有付款记录
        List<Payment> existingPayments = paymentRepository.findByOrderId(orderId);
        for (Payment p : existingPayments) {
            if (p.getPaymentStatus() == Payment.PaymentStatus.SUCCESS || 
                p.getPaymentStatus() == Payment.PaymentStatus.COMPLETED) {
                throw new RuntimeException("订单已付款");
            }
        }
        
        // 创建付款记录
        Payment payment = new Payment();
        payment.setOrder(order);
        payment.setPaymentNumber(generatePaymentNumber());
        payment.setAmount(order.getTotalAmount());
        payment.setPaymentMethod(Payment.PaymentMethod.valueOf(paymentMethod));
        payment.setPaymentStatus(Payment.PaymentStatus.SUCCESS);
        payment.setTransactionId(generateTransactionId());
        
        Payment savedPayment = paymentRepository.save(payment);
        
        // 更新订单状态
        order.setOrderStatus(Order.OrderStatus.PAID);
        orderRepository.save(order);
        
        return savedPayment;
    }
    
    /**
     * 处理退款
     */
    public Payment processRefund(Long orderId, String refundReason) {
        Optional<Order> orderOpt = orderRepository.findById(orderId);
        if (orderOpt.isEmpty()) {
            throw new RuntimeException("订单不存在");
        }
        
        Order order = orderOpt.get();
        if (order.getOrderStatus() != Order.OrderStatus.REFUNDED) {
            throw new RuntimeException("订单未处于退票状态");
        }
        
        // 查找原付款记录
        List<Payment> originalPayments = paymentRepository.findByOrderIdAndPaymentStatus(
            orderId, Payment.PaymentStatus.SUCCESS);
        
        if (originalPayments.isEmpty()) {
            throw new RuntimeException("未找到原付款记录");
        }
        
        Payment originalPayment = originalPayments.get(0);
        
        // 检查是否已有退款记录
        List<Payment> existingRefunds = paymentRepository.findByOrderIdAndPaymentType(
            orderId, Payment.PaymentType.REFUND);
        
        if (!existingRefunds.isEmpty()) {
            throw new RuntimeException("已存在退款记录");
        }
        
        // 创建退款记录
        Payment refund = new Payment();
        refund.setOrder(order);
        refund.setPaymentNumber(generatePaymentNumber());
        refund.setAmount(originalPayment.getAmount().negate()); // 负数表示退款
        refund.setPaymentMethod(originalPayment.getPaymentMethod());
        refund.setPaymentType(Payment.PaymentType.REFUND);
        refund.setPaymentStatus(Payment.PaymentStatus.SUCCESS);
        refund.setTransactionId(generateTransactionId());
        refund.setRefundReason(refundReason);
        
        return paymentRepository.save(refund);
    }
    
    /**
     * 获取订单付款记录
     */
    public List<Payment> getPaymentsByOrderId(Long orderId) {
        return paymentRepository.findByOrderId(orderId);
    }
    
    /**
     * 获取用户所有付款记录
     */
    public List<Payment> getPaymentsByUserId(Long userId) {
        return paymentRepository.findByOrderUserIdOrderByCreatedAtDesc(userId);
    }
    
    private String generatePaymentNumber() {
        String timestamp = LocalDateTime.now().toString().replaceAll("[^0-9]", "");
        String random = String.valueOf((int)(Math.random() * 9000) + 1000);
        return "PAY" + timestamp.substring(0, Math.min(14, timestamp.length())) + random;
    }
    
    private String generateTransactionId() {
        return "TXN" + System.currentTimeMillis() + String.valueOf((int)(Math.random() * 1000));
    }
}